<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1 id="main" price="900"> Jquery </h1>
    <h1> hello world </h1>

</body>
<script>
    (function () {
        var jquery = window.$ = function (xzq) {
            return new jquery.prototype.init(xzq);
        }

        jquery.prototype = {
            init: function (xzq) {
                if (typeof xzq === 'string') {  // 判断是否为选择器字符串
                    let arr = document.querySelectorAll(xzq);
                    Array.prototype.push.apply(this, arr);
                } else if (xzq instanceof Element) {  // 判断是否为元素节点
                    this[0] = xzq;
                    this.length = 1;
                }
                return this;
            },
            html: function (v) {
                if (v == undefined) {
                    return this[0].innerHTML;
                }
                for (let i = 0; i < this.length; i++) {
                    this[i].innerHTML = v;
                }
            },
            css: function (attr, val) {
                if (val == undefined) { //空
                    return this[0].style[attr];
                }
                for (var i = 0; i < this.length; i++) {
                    this[i].style[attr] = val;
                }
                //实现链式
                return this;
            },
            eq: function (index) {
                var element = this[index];
                return $(element);
            },
            attr: function (name, value) {
               
                for (var i = 0; i < this.length; i++) {
                    this[i].style[name]=value;
                }
                return this; 
            },
            each: function (callback) {
                for (var i = 0; i < this.length; i++) {
                    callback.call(this[i], i, this[i]);
                }
                return this;
            }
        }
        

        jquery.prototype.init.prototype = jquery.prototype;

    })();


    $('h1').eq(1).css("background-color","yellow");
    $('h1').eq(0).css("background-color","red");
    $('#main').attr('price',9);
    $('h1').each(function (index, element) {
        console.log(index + ': ' + element.innerHTML);
    });
</script>

</html>
